#include "ringbuf.h"

void initRingBuf(RINGBUF_CTRL_S *ringbufctrl, uint8_t *buf, uint32_t len)
{
    if(ringbufctrl == NULL || buf == NULL)
        return ;
    
    ringbufctrl->buf = buf;
    ringbufctrl->buflen = len;
    ringbufctrl->read = 0;
    ringbufctrl->write = 0;
}
void deinitRingBuf(RINGBUF_CTRL_S *ringbufctrl)
{
    if(ringbufctrl == NULL)
        return ;
    ringbufctrl->buf = NULL;
    ringbufctrl->buflen = 0;
    ringbufctrl->read = 0;
    ringbufctrl->write = 0;
}
int8_t checkRingBuf(RINGBUF_CTRL_S *ringbufctrl)
{
    if(ringbufctrl == NULL || \
        ringbufctrl->buf == NULL || \
        ringbufctrl->buflen == 0)
        return -1;
    return 0;
}
int8_t pushRingBuf(RINGBUF_CTRL_S *ringbufctrl, uint8_t buf)
{
    if(checkRingBuf(ringbufctrl) != 0)
        return -1;
    if((ringbufctrl->write + 1) % (ringbufctrl->buflen) == ringbufctrl->read)
        return -1;
    ringbufctrl->buf[ringbufctrl->write] = buf;
    ringbufctrl->write = (ringbufctrl->write + 1) % (ringbufctrl->buflen);
}
int8_t popRingBuf(RINGBUF_CTRL_S *ringbufctrl, uint8_t *buf)
{
    if(checkRingBuf(ringbufctrl) != 0)
        return -1;
    if(ringbufctrl->write == ringbufctrl->read)
        return -1;
    if(buf != NULL)
        *buf = ringbufctrl->buf[ringbufctrl->read];
    ringbufctrl->read = (ringbufctrl->read + 1) % (ringbufctrl->buflen);
}

int8_t glanceRingBuf(RINGBUF_CTRL_S *ringbufctrl, uint8_t *buf)
{
    if(checkRingBuf(ringbufctrl) != 0)
        return -1;
    if(ringbufctrl->write == ringbufctrl->read)
        return -1;
    if(buf != NULL)
        *buf = ringbufctrl->buf[ringbufctrl->read];
}
